package reporting;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import core.SeleneseTestCaseEx;
import static util.ConstantCollection.*;
import util.*;

class HtmlReport extends TemplateReport{

	private FileWork fw = FileWork.getInstance();
	private TestConfiguration tc = TestConfiguration.getInstance();
	private Util u = new Util();
	private String i_logRightFilename = "right.htm";
	private String i_logLeftFilename = "left.htm";
	private String i_logMainFilename = "log.htm";
	private Integer i_logRightIterator;
	private Integer i_logIterator = 0;
	private Integer idDiv = 0;
	private Integer errId = 0;
	private Integer trcId = 0;

	public HtmlReport(String name) {
		super(name);
		String tempPath;
		String tempIcons;
		tempPath = u.getFullPathToLog("datetime") + "html/";

		//String releaseIndexPath = indexPath + tc.getEnv("release") + "/" + "index.htm";
		
		if(!fw.existsFileOrDir(tempPath)){
		   	fw.createDir(tempPath);
		}
		
		tempIcons = tempPath + "icons/";
		if(!fw.existsFileOrDir(tempIcons)){
			fw.createDir(tempIcons);
		}
		
		for(Integer i = 0; i < 8; i++){
			try {
				fw.copy("res/reporting/html/" + i.toString() + ".ico", tempIcons);
	    	} catch (IOException e) {
	    	    System.err.println(e.getMessage());
	    	}
		}
		
		tempPath = tempPath + getName();  
		if(!fw.existsFileOrDir(tempPath)){
			fw.createDir(tempPath);
		}
		
		generateIndexFile();
	}
			
	/**
	 * Gets index for current event to report it to HTML log (event index is not displayed in log, but it is used internally for link references).
	 * and increases event iterator by 1.
	 * @return string, containing value of the current event index.
	 */
	private String getLogIterator(){
		String result;
		i_logIterator++;
		result = i_logIterator.toString();
		return result;
	}

	/** Actually gets path (not name!) to HTML log file, containing detailed event descriptions.
	 * @return string, containing full path to the HTML log file with detailed event descriptions.
	 */
	private String getLogDetailsFileName(){
		return fileGenerateResPath(i_logRightFilename);
	}
	
	/** Actually gets path (not name!) to HTML log file with event contents.
	 * @return string, containing full path to the HTML log file with event contents.
	 */
	private String getLogContentsFileName(){
		return fileGenerateResPath(i_logLeftFilename);
	}


	/**
	 * Starts new log file when current log file size exceeds limit (<see cref="LOG_SWAP_SIZE"/> constant) and adds reference to the new log file. 
	 */
	private void swapLogFile(){
	    System.out.println("DONE\tSwapping log file '" + i_logRightFilename + "'");
		i_logRightIterator = i_logRightIterator + 1;
		i_logRightFilename = "right" + i_logRightIterator.toString() + ".htm";
	}
	
	/**
	 * Creates HTML log file with all headers.
	 */
	private void createReportHTML(){
		i_logRightIterator = 0;
		String text;
		text = "<HTML><head><title>" + u.encodeHTML(tc.getEnv("_testtitle")) + " - Test Report</title><META http-equiv=Content-Type content='text/HTML; charset=windows-1251'></head>\n"; 
		text = text + "<frameset framespacing='0'  frameborder='1'> <frameset  cols='30%, 70%' frameborder='1' framespacing='0' bordercolor='#ffffff'>\n";
		text = text + "<frame src='" + i_logLeftFilename + "'  name='LeftFrame' scrolling='yes' frameborder='1'>";
		text = text + "<frame src='" + i_logRightFilename + "' name='RightFrame'></frameset></frameset><noframes> <BODY bgcolor='#f5f5f5'> <p>Need Frames</p>\n"; 
		text = text + "</BODY></noframes></HTML>";
		fw.writeFile(fileGenerateResPath(i_logMainFilename), text);
	}
		
	/**
	 * @param status
	 * @return
	 */
	public String getStatusColor(int status){
	   	String statusColor;
	   	switch(status){
	   		case 0: 
	   			statusColor = "blue";
	   			break;
			case 1:
				statusColor = "gray";
				break;
			case 2:
				statusColor = "black";
				break;
	        case 3:
	        	statusColor = "green";
	        	break;
	        case 4:
	        	statusColor = "gold";
	        	break;
	        case 5:
	        	statusColor = "FF7AFF";
	        	break; //pink
	        case 6:
	        	statusColor = "red";
	        	break;
	        case 7:
	        	statusColor = "8700FF";
	        	break; //purple
	        default:
	        	statusColor = "red";
	        break;
	   	}
	   	return statusColor;
	}
	
    public String getStatusImage(int status){
        return "<img class='status' src='../icons/" + Integer.toString(status) +  ".ico' name='" + getStatusName(status).toLowerCase() + "'>";
        
   }
	    
	private String fileGenerateResPath(String fileName){
	  	return u.getFullPathToLog("datetime") + "html/" + getName() + "/" + fileName;
	}
	 
    /**Gets the full content of the "left.htm" HTML log file and processed it by <see cref="htmlTextGetBody"/> function.
     * @return String, contains BODY of the "left.htm" HTML log file.
     */
    private String getContentsHtml(){
    	String text;
   		if(fw.existsFileOrDir(getLogContentsFileName())){
   			//Load log file
    		text = fw.readFile(getLogContentsFileName());
    		text = htmlTextGetBody(text);
    	}
    	else{
    		//Init log file
    		createReportHTML();
    		text = "<STYLE TYPE='text/css'>" + "\n\t" + 
    		              ".{" + "\n\t\t" + 
    		              		"font-family:arial;" + "\n\t\t" + 
    		              		"text-decoration:none" + "\n\t" + 
    		              	"}" + "\n\t" + 
    		              	"a{" + "\n\t\t" + 
    		              		"font-family:arial;" + "\n\t\t" + 
    		              		"font-size: 10pt;" + "\n\t\t" + 
    		              		"color:black;" + "\n\t\t" + 
    		              		"text-decoration:none" + "\n\t" + 
    		              	"}" + "\n\t" + 
    		              	"a:visited{" + "\n\t\t" + 
    		              		"font-family:arial;" + "\n\t\t" + 
    		              		"font-size: 10pt;" + "\n\t\t" + 
    		              		"color:black;" + "\n\t\t" + 
    		              		"text-decoration:none" + "\n\t" + 
    		              	"}" + "\n\t" +
    		              	"table.step{" + "\n\t\t" +
    		              		"border-spacing:0px;" + "\n\t\t" +
    		              		"border-style:none;" + "\n\t" +
    		              	"}" + "\n\t" +
    		              	"td.status{" + "\n\t\t" +
    		              		"padding:0px;" + "\n\t\t" +
    		              		"marging:0px;" + "\n\t\t" +
    		              		"border-style:none;" + "\n\t" +
    		              	"}" + "\n\t" +
    		              	"td.steplink{" + "\n\t\t" +
    		              		"margin:0px;" + "\n\t\t" +
    		              		"padding:0px;" + "\n\t\t" +
    		              		"border-style:none;" + "\n\t\t" +
    		              		"white-space: nowrap;" + "\n\t\t" +
    		              		"line-height: 50%;" + "\n\t\t" +
    		              		"font-weight: bold;" + "\n\t" +
    		              	"}" + "\n\t" +
    		              	"span.id{" + "\n\t\t" +
    		              		"font-family:arial;" + "\n\t\t" +
    		              		"font-size:12;" + "\n\t\t" + 
    		              		"color:blue;" + "\n\t\t" +
    		              		"border-style:none;" + "\n\t" +
    		              	"}" + "\n\t" +
    		              	"span.stepname{" + "\n\t\t" +
    		              		"font-family:arial;" + "\n\t\t" +
    		              		"font-size:12;" + "\n\t\t" +
    		              		"color:blue;" + "\n\t\t" +
    	    					"border-style:none;" + "\n\t" +
    	    				"}" + "\n\t" +
    	    				"img.status{" + "\n\t\t" +
    	    					"border-style:none;" + "\n\t\t" +
    	    					"width:15;" + "\n\t\t" +
    	    					"padding:0px;" + "\n\t" +
    	    				"}" + "\n\t" +
    	    				"a.summary{" + "\n\t\t" +
    	    					"color:D8A170;" + "\n\t\t" +
    	    					"font-size:16pt;" + "\n\t\t" +
    	    					"font-weight: bold;" + "\n\t\t" + 
    	    					"white-space: nowrap;" + "\n\t\t" +
    	    					"text-decoration: underline;" + "\n\t" +
    	    				"}"	+ "\n" +
    				"</STYLE>" + "\n" +
    					
    				"<a class='summary' href='summary.htm' target='RightFrame'>Test Summary</a>" + "\n" +
    				"<BR>" + "\n" +
    				"<BR>" + "\n" + 
    				"<a href='" + i_logRightFilename + "#0' class='text' target='RightFrame' style='white-space: nowrap;font-weight: bold;'>Test Log Started</a>" + "\n";
    	}
   		return text;
    }

    /**Gets the full content of the "log.htm" HTML log file and processed it by <see cref="htmlTextGetBody"/> function.
     * @return String, contains BODY of the "log.htm" HTML log file.
     */
    private String getLogHtml(){
    	String text;
    	if(fw.existsFileOrDir(getLogDetailsFileName())){
    		//Load log file
    		text = fw.readFile(getLogDetailsFileName());
    		text = htmlTextGetBody(text);
    	}
    	else{
    		//Init log file
			text = "<script type='text/javascript'>" + "\n\t";
			text = text.concat("function showDiv(div){") + "\n\t";
			text = text.concat("	if (document.getElementById(div).style.display=='none')") + "\n\t";
			text = text.concat("		document.getElementById(div).style.display='block';") + "\n\t";
			text = text.concat("	else") + "\n\t";
			text = text.concat("		document.getElementById(div).style.display='none';") + "\n\t";
			text = text.concat("}") + "\n\t";
			text = text.concat("function ShowDivs(elem){") + "\n\t";
			text = text.concat("	var elements=document.getElementsByTagName('div');") + "\n\t";
			text = text.concat("	if (elem.checked)") + "\n\t";
			text = text.concat("		var t='block';") + "\n\t";
			text = text.concat("	else") + "\n\t";
			text = text.concat("		var t='none';") + "\n\t";
			text = text.concat("		for (var i=0;  i<elements.length; i++){") + "\n\t";
			text = text.concat("			elements[i].style.display=t;") + "\n\t";
			text = text.concat("		}") + "\n\t";
			text = text.concat("}") + "\n";
			text = text.concat("</script>") + "\n";
			
	        text = text + ("<style>\n");
	        text = text + ("  TABLE {");
	        text = text + ("    border: 4px double black;\n");
	        text = text + ("    border-collapse: collapse;\n");
	        text = text + ("    font-family:Arial;\n");
	        text = text + ("    background:#CCCCCC\n");
	        text = text + ("  }");
	        text = text + ("  TH {\n");
	        text = text + ("    text-align: center;\n");
	        text = text + ("    padding: 5px;\n");
	        text = text + ("    border: 1px solid black\n");
	        text = text + ("  }\n");
	        text = text + ("  TD {\n");
	        text = text + ("    padding: 5px;\n");
	        text = text + ("    border: 1px solid black\n");
	        text = text + ("  }\n");
	        text = text + (".head{color:#000000;font-size:11pt;font-weight:bold}\n");
	        text = text + (".name{color:#000000;font-size:10pt;font-family:Arial;font-weight:bold}\n");
	        text = text + (".create{color:#0066CC;font-size:11pt;font-weight:bold}\n");
	        text = text + (".rez{font-size:11pt;font-weight:bold}\n");
	        text = text + (".steep{background: #FFFFFF;border: 0px solid black;font-size:9pt}\n");
	        text = text + (".resoult{font-size:9pt;background: #FFFFFF;border: 0px solid black;border-left: 1px solid black;border-right: 1px solid black;font-weight:bold}\n");
	        text = text + (".coments{background:#FFFFFF;color:#000000;font-size:10pt;font-family:Arial;font-weight:bold;font-style:italic}\n");
	        text = text + (".cloc{color:#000000;font-size:9pt;background:#FFFFFF}\n");
	        text = text + (".nom{font-size:14pt;font-family:Courier;font-weight:lighter;background:#b7b7b7}\n");
	        text = text + ("</style>\n\n");
			
			text = text.concat("<a name='0' target='RightFrame'/>");
			
    		text = text.concat("<table align='center' style='border:1px;background:#FFFFFF'>");
    		text = text.concat("\n");
    		text = text.concat("	<tr style='border:0px'>");
    		text = text.concat("\n");
    		text = text.concat("		<td colspan=2 style='border:0px' valign='center' width='300'><b style='font-size:25pt;color:808080'>" + tc.getEnv("_testtitle") + "</b></td>");
    		text = text.concat("\n");
    		text = text.concat("	</tr>");
    		text = text.concat("\n");
    		text = text.concat("	<tr style='border: 1px solid black'>");
    		text = text.concat("\n");
    		text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt;'>Test name:</b></td>");
    		text = text.concat("\n");
    		text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + tc.getEnv("_testname") + "</b></td>");
    		text = text.concat("\n");
    		text = text.concat("	</tr>");
    		text = text.concat("\n");
    		text = text.concat("	<tr style='border: 1px solid black'>");
    		text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Product:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + tc.getEnv("product") + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	text = text.concat("	<tr style='border: 1px solid black'>");
    		text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Release:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + tc.getEnv("release") + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	
    		text = text.concat("	<tr style='border: 1px solid black'>");
    		text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Server:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + SeleneseTestCaseEx.getServerName() + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	text = text.concat("	<tr style='border: 1px solid black'>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Browser:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + SeleneseTestCaseEx.getBrowser() + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	text = text.concat("	<tr style='border: 1px solid black'>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Time zone:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + u.getTimeZone() + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	text = text.concat("	<tr style='border: 1px solid black'>");
	    	text = text.concat("\n");
	    	text = text.concat("        <td style='border: 1px solid black' align='left'><b style='font-size:12pt'>Run started:</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("		<td style='border: 1px solid black' valign='center'><b style='font-size:9pt;color:blue'>" + u.getDateTimeNow() + "</b></td>");
	    	text = text.concat("\n");
	    	text = text.concat("	</tr>");
	    	text = text.concat("\n");
	    	text = text.concat("</Table>");
	    	text = text.concat("\n");
	    	text = text.concat("<br><br><hr><br>");
	    	text = text.concat("\n");
	    	text = text.concat("<input type='checkbox' name='checkbox' id='checkbox' onClick='ShowDivs(this)'/>Show all problems!<br>");

    	}
    	return text;
    }
	    
    /** Converts specified <i>eventStatus</i> into appropriate HTML string.
     * @param eventStatus Status message
     * @return HTML formatted string, contains information about status.
     */
    private String getStatusHTML(Integer eventStatus){
    	return "<FONT style='color:" + getStatusColor(eventStatus) + "'>" + getStatusName(eventStatus) + "</FONT>";
    }
	    
    /** Remove all BODY and HTML tags from <htmlString> source text, <htmlString> is assumed to be framework-generated HTML file's text
     * @param htmlString Input html
     * @return <htmlString> cleaned from <BODY>, </BODY>, <HTML>, </HTML> substrings
     */
    private String htmlTextGetBody(String htmlString){
    	String result = null;
    	if (htmlString == null){
    		result = ""; 
    	}
    	else{
    		try{
    	   		String t;
    	   		t = htmlString;
    	   		t = t.replace("<HTML>", "");
    	   		t = t.replace("<HTML>", "");
    	   		t = t.replace("</HTML>", "");
    	   		t = t.replace("<BODY>", "");
    	   		t = t.replace("</BODY>", "");
    	   		t = t.replace("<html>", "");
    	   		t = t.replace("</html>", "");
    	   		t = t.replace("<body>", "");
    	   		t = t.replace("</body>", "");
    	   		result = t;
    		}
    		catch(Exception e){
    			System.err.println("HtmlTextGetBody :: " + e.getMessage());
    		}
    	}
    	return result;
    }
    
    private void reportEventWText_HTML(TCStep step){
    	String mainText = "";
		String logMainText;
		logMainText = getLogHtml();
		String eventIndex;
		eventIndex = getLogIterator();
		final String ACTION_TITLE = "Input/Action";
		final String EXPECTED_TITLE = "Expected Result";
		String detail = "";
    	String lastTypeItem = "action";
    	int sumStep = 0;
    	int sumRow = 0;
		String inputAction = "";
		String actionStep = "";

		for (Iterator<StepItem> it = step.getItemCollection().iterator(); it.hasNext(); sumRow++) {
    		StepItem item = it.next();
    		int status = item.getStatus();
    		sumStep = 0;
    		actionStep = "";
     		inputAction = "";
    		if (item.getType() == "action") {
           	 	if (lastTypeItem == "cp") {
           	 		lastTypeItem = "action";
           	 	}
       	 		sumStep++;
       	 		inputAction = ("<tr valign='middle'>");
       	 		inputAction = inputAction + ("<td class='name' style='font-size:8pt' rowspan='" + sumStep + "'>" + ACTION_TITLE + "</td>\n"); 
       	 		if(status <= STATUS_PASS) {
           	 		actionStep = actionStep + ("<td class='steep'>" + item.getStepNum() + ". " + item.getDescription() + "</td>\n");
           	 		actionStep = actionStep + ("<td class='resoult' align='center' style='color: " + getStatusColor(status) + "'>");
       	 			actionStep = actionStep + getStatusName(status) + "</td>" + "</tr>\n";
       	 		} else {
       	 			idDiv++;
       	 			errId++;
           	 		actionStep = actionStep + ("<td class='steep'>" + item.getStepNum() + ". " + item.getDescription() + ".<br>");
           	 		actionStep = actionStep + ("  <div style='display:none' id='div" + idDiv.toString() + "'>");
           	 		actionStep = actionStep + ("    <table style='background:#FFFFFF;border: 1px black' width='350'><tr><td><FONT style='font-family:Arial;font-size:9pt'>" + item.getErrorDescription().toString() + "<FONT></tr></td>");
           	 		
           	 		if (item.getScreenshot() != null) {
           	 			actionStep = actionStep + ("      <tr><td><a style='text-decoration:none; font-size:9pt' href='../../source/scrsht/" + item.getScreenshot() + "' target='_blank' onClick=\"popupWin=window.open(this.href, 'screenshot', 'location,width=700,height=500,top=0');popupWin.focus();return false;\">Show error screenshot</a></td></tr>\n");
           	 		}
           	 		
       	 			if (status == STATUS_ERROR) {
       	 				trcId++;
       	 				actionStep = actionStep + ("      <tr><td><a style='text-decoration:none; font-size:9pt' href='../../source/trace/" + item.getPathToCommonTrace() + "' target='_blank' onClick=\"popupWin=window.open(this.href, 'problem', 'location,width=700,height=500,top=0');popupWin.focus();return false;\">Show error description</a></td></tr>\n");       	 				
       	 			}
       	 			
           	 		actionStep = actionStep + ("    </table>\n");
           	 		actionStep = actionStep + ("  </div>\n");
           	 		actionStep = actionStep + ("</td>\n");
           	 		actionStep = actionStep + "<td class='resoult' align='center'><a href=\"javascript:showDiv('div" + idDiv.toString() + "')\" style='text-decoration:none;color:" + getStatusColor(status) + "'>" + getStatusName(item.getStatus()) + "</a></td>";
       	 		}
    		} else if (item.getType() == "cp") {
    			//if (lastTypeItem == "" || lastTypeItem == "action") {
    				lastTypeItem = "cp";
    				detail = detail + ("<tr valign='middle'>\n");
    				detail = detail + ("  <td class='name' style='font-size:8pt'>" + EXPECTED_TITLE + "</td>\n");
    			//}
        		
    			if(status <= STATUS_PASS) {
        			detail = detail + ("  <td class='coments'>" + item.getDescription() + "</td>\n");
        			detail = detail + ("  <td class='resoult' align='center' style='color: " + getStatusColor(status) + "; border: 1px solid black'>" + getStatusName(status) + "</td>\n");
                 	detail = detail + ("</tr>\n");
        		} else {
        			idDiv++;
        			errId++;
        			detail = detail + ("  <td class='coments'>" + item.getDescription() + "\n");
               		detail = detail + ("  <div style='display:none' id='div" + idDiv.toString() + "'>");
               		detail = detail + ("    <table style='background:#FFFFFF;border: 1px black' width='350'>");
               		detail = detail + ("      <tr><td><FONT style='font-family:Arial;font-size:9pt'>" + item.getErrorDescription().toString() + "<FONT></tr></td>");
               	 		
               		if (item.getScreenshot() != null) {
               			detail = detail + ("      <tr><td><a style='text-decoration:none; font-size:9pt' href='../../source/scrsht/" + item.getScreenshot() + "' target='_blank' onClick=\"popupWin=window.open(this.href, 'screenshot', 'location,width=700,height=500,top=0');popupWin.focus();return false;\">Show error screenshot</a></td></tr>\n");
               		}
               	 		
               		if (status == STATUS_ERROR) {
               			trcId++;
                 		detail = detail + ("      <tr><td><a style='text-decoration:none; font-size:9pt' href='../../source/trace/" + step.getId() + "_" + trcId.toString() + ".txt' target='_blank' onClick=\"popupWin=window.open(this.href, 'problem', 'location,width=700,height=500,top=0');popupWin.focus();return false;\">Show error description</a></td></tr>\n");
               		}
               	 		
               		detail = detail + ("    </table>\n");
               		detail = detail + ("  </div>\n");
              		detail = detail + ("</td>\n");
              		detail = detail + ("  <td class='resoult' align='center' style='border: 1px solid black'><a href=\"javascript:showDiv('div" + idDiv.toString() + "')\" style='text-decoration:none;color:" + getStatusColor(status) + "'>" + getStatusName(status) + "</a></td></tr>\n");
        			errId = 0;
        		}
    		}	
       	 	detail = detail + inputAction + actionStep + "\n";           	 	
    	}
		
		mainText = logMainText + createHead(step.getStatus(), sumRow, step.getId(), step.getName(), eventIndex) + detail + "</table><br>";
		logMainText = "<HTML>\n<BODY>" + (mainText + "\n</BODY>\n</HTML>");
		fw.writeFile(getLogDetailsFileName(), logMainText);
		
		//Write contents
		String logContentsText;
		logContentsText = getContentsHtml();
		String contents = "<table class='step'>" + "\n\t" + 
		              "<tr>" + "\n\t\t" + 
		                 "<td class='status'>" + "\n\t\t\t" +
		                 	getStatusImage(step.getStatus()) + "\n\t\t" +
		                 "</td>" + "\n\t\t" +
		                 "<td class='steplink'>" + "\n\t\t\t" +
		                 	"<a href='" + i_logRightFilename + "#" + eventIndex + "' class='text' target='RightFrame'>" + "\n\t\t\t\t" +
		                 		"<span class='id'>" + step.getId() + ".</span>" + "\n\t\t\t\t" +
		                 		"<span class='stepname'>" + u.encodeHTML(step.getName()) + "</span>"  + "\n\t\t\t" +
		                 	"</a>"  + "\n\t\t" +
		                 "</td>" + "\n\t" +
		                 "</tr>" + "\n" +
		                 "</table>";
		
		logContentsText = "<HTML>\n<BODY>" + logContentsText + (contents + "</BODY>\n</HTML>");
		fw.writeFile(getLogContentsFileName(), logContentsText);
		byte[] utf8 = null;
		int byteCount = 0;
		try {
		  utf8 = logMainText.getBytes("UTF-8");
		  byteCount = utf8.length;
		}
		catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		}
		if( byteCount > LOG_SWAP_SIZE){
			swapLogFile();
		}
    }
   
    private String createHead(int eventStatus, int sumStep, String eventId, String step, String eventIndex) {
    	String mainText = "";
    	sumStep+=1;
    	mainText = mainText + ("<table bgcolor='CCCCCC' align='center'>\n");
        mainText = mainText + ("  <tr class='head' valign='middle' bgcolor='" + getStatusColor(eventStatus) + "'>\n");
        mainText = mainText + ("    <th align='center' width='50'>ID<a name='" + eventIndex + "' target='RightFrame'/>\n</th>\n");
        mainText = mainText + ("    <th align='center' colspan='2' width='500'>DETAILS</th>\n");
        mainText = mainText + ("    <th align='center' width='50'>STATUS</th>\n");
        mainText = mainText + ("    <th align='center' width='50'>TIME</th>\n");
        mainText = mainText + ("  </tr>\n");
        mainText = mainText + ("  <tr valign='middle'>\n");
        mainText = mainText + ("    <td class='nom' align='center' rowspan='" + sumStep + "'>" + eventId + ".</td>\n");
        mainText = mainText + ("    <td class='name' width='105'>Name</td>");
        mainText = mainText + ("    <td class='create' width='395'>" + u.encodeHTML(step) + "</td>\n");
        mainText = mainText + ("    <td class='rez' align='center'>" + getStatusHTML(eventStatus) + "</td>\n");
        mainText = mainText + ("    <td class='cloc' align='center' rowspan='" + sumStep + "'>" + u.getTimeNow() + "</td>\n");
        mainText = mainText + ("  </tr>\n");     
        return mainText;
    }
    
	public void reportStep(TCStep step) {
		reportEventWText_HTML(step);
	}
	
	
	/** Generation 'index.htm' file.
	 * Remark:
	 * There are two paths 'index.htm' file generation.
	 * 1 - last result for duplicate test titles (uses by default)
	 * 2 - separate result for duplicate test titles, with grouping result by test title and time start execution.
	 */
	private void generateIndexFile() {
		/* 1.Check if exists 'index.htm' file, if does not, then get text from 'res\reporting\html\index_pattern.htm', 
		else, get content existing file. 
		   2.Get content <TABLE>...</TABLE> with use regexp.
	   	   3.Genetate new content:
	   	   	PATH1 (Env("replaceindexhtmlog") = true):
		   	Find the test title, replace path if exists, or add new row to table
		   	PATH2 (Env("replaceindexhtmlog") = false):
		   	3.1.Parse table and store data to array
		   	3.2.Sorting data in array by 'Test name', 'Start time'
		   	3.3.Generate new html table
		   	3.4.Replace html table with use regexp in source html text
		   4.Save html text to file "index.htm"
		*/
		
		String htmlText = "";
		String testIndexPath = "";
		testIndexPath =  u.getFullPathToLog("release") + "index.htm";
						
		if(!(fw.existsFileOrDir(testIndexPath) && (fw.readFile(testIndexPath) != ""))){
    		try {
    			fw.copy("res\\reporting\\html\\index_pattern.htm", testIndexPath);
    		} catch(Exception e) {
    			System.err.println("generateIndexFile :: " + e.getMessage());
    		}
    	}
		
		htmlText = fw.readFile(testIndexPath);
		htmlText = generateNewHtmlTable(testIndexPath, htmlText);
		fw.writeFile(testIndexPath, htmlText);
	}
	
	
	
	private String generateNewHtmlTable(String testIndexPath, String htmlText){
		String res = "";
		String pattern = "(?s)(?i)(.*)(<\\s*[aA].*>.*" + tc.getEnv("_testtitle") + ".*?</\\s*[aA]\\s*>)(.*)";	
		if (tc.getEnv("replaceindexhtmlog").toLowerCase().contentEquals("true")){
			if (htmlText.matches(pattern)){
				res = htmlText.replaceFirst(pattern, "$1<a href='" + "../../" + u.getPathToLog("datetime") + "html/main/log.htm" + "'>" + tc.getEnv("_testtitle") +"</a>$3");
			} else {
				Integer i = 1;
				while(htmlText.contains(i.toString() + ".")) {
					i++;
				}
				
				String newRec = "<TR>" + "\n\t\t" +
				"<TD class='ID'>" + "\n\t\t\t" +
						i.toString() + "." + "\n\t\t" +
						"</TD>" + "\n\t\t" +
						"<TD class='testLink'>" + "\n\t\t\t" +
						"<a href='" + "../../" + u.getPathToLog("datetime") + "html/main/log.htm" + "'>" + tc.getEnv("_testtitle") +"</a>" + "\n\t\t" +
						"</TD>" + "\n\t" +
						"</TR>" + "\n\t"; 
				
				res = htmlText.replaceFirst("(?s)(?i)(.*)(</\\s*table\\s*>)(.*)", "$1" + newRec + "$2$3");
			}
			
		} else {
			//TODO needs to develop in future
		}
		return res;
	}

}